<?php

class Admin_Model_Module
{
	public static function activate($idname, $active = TRUE)
	{
		if (empty($idname)) {
			throw new Exception('Invalid id name');
		}

		if (self::_activate($idname, $active) === FALSE) {
			//TODO: show a message that tells that the module could not be activate and the reason why
			return FALSE;
		}

		$componentDbTable = new Euso_Model_DbTable_ModuleRegistry();

		$dbData = array(
			'active' => $active ? 1 : 0,
		);

		$updRows = $componentDbTable->update($dbData, array('idname= ?' => $idname));

		if ($updRows != 1) {
			$module = Kernel::getInstance()->getModule($idname, FALSE);
			if ($module instanceof Euso_Module) {
				$dbData['idname'] = $idname;
				$dbData['version'] = $module->getVersion();
				$insetId = $componentDbTable->insert($dbData);
				if ($insetId < 1) {
					throw new Exception('Query error');
				}
			} else {
				throw new Exception('Module not found');
			}
		}

		return TRUE;
	}

	protected static function _activate($idname, $active = TRUE)
	{
		require_once MODULE_PATH .'/'. $idname .'/install.php';

		$hookFunc = 'module_'. $idname;

		if ($active) {
			$hookFunc .= '_activate';
		} else {
			$hookFunc .= '_deactivate';
		}

		return $hookFunc(array());
	}
}
